<template>
  <div class="container">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select" clearable @clear="getUsers">
            <el-button slot="append" icon="el-icon-search" @click="getUsers" />
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="default" @click="addFormDialogVisible = true">添加用户</el-button>

        </el-col>
      </el-row>

      <el-table :data="usersList" border stripe>
        <el-table-column type="index" align="center" />
        <el-table-column label="姓名" prop="username" align="center" />
        <el-table-column label="邮箱" prop="email" align="center" />
        <el-table-column label="电话" prop="mobile" align="center" />
        <el-table-column label="角色" prop="role_name" align="center" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="handleSwitchChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false" transition="">
              <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false" transition="">
              <el-button type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="角色设定" placement="top" :enterable="false" transition="">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

    </el-card>

    <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addFormDialogVisible"
      width="40%"
      center
      @close="dialogClose"
    >
      <el-form ref="addFormRefs" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="用户名称：" prop="username">
          <el-input v-model="addForm.username" clearable />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="addForm.password" type="password" clearable />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="addForm.email" clearable />
        </el-form-item>
        <el-form-item label="手机：" prop="mobile">
          <el-input v-model="addForm.mobile" clearable />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editFormDialogVisible"
      width="40%"
      center
      @close="editDialogClose"
    >
      <el-form ref="eidtFormRefs" :model="eidtForm" :rules="eidtFormRules" label-width="100px">
        <el-form-item label="用户名称：">
          <el-input v-model="eidtForm.username" clearable disabled />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="eidtForm.email" clearable />
        </el-form-item>
        <el-form-item label="手机：" prop="mobile">
          <el-input v-model="eidtForm.mobile" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editFormConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    // const checkMail = (rule, val, cb) => {
    //   // 错误的邮箱验证
    //   const regMail = /^(a-zA-Z0-9_-)+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

    //   if (regMail.test(val)) {
    //     return cb()
    //   }
    //   cb(new Error('请输入正确的邮箱'))
    // }

    // 验证电话
    // const checkMobile = (rule, val, cb) => {
    //   const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

    //   if (regMobile.test(val)) {
    //     return cb()
    //   }
    //   cb(new Error('请输入正确的电话号码'))
    // }

    return {
      queryInfo: {
        query: '',
        // 当前页码数
        pagenum: 1,
        // 每页显示多少条
        pagesize: 2
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入您的用户名称', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名称长度必须为3~15个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入您的密码', trigger: 'blur' },
          { min: 3, max: 10, message: '密码长度必须为3~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入您的邮箱', trigger: 'blur' }
          // { validator: checkMail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入您的电话', trigger: 'blur' }
          // { validator: checkMobile, trigger: 'blur' }

        ]
      },
      usersList: [],
      // 总共多少条数据
      total: 0,
      addFormDialogVisible: false,
      // 编辑用户数据对象
      eidtForm: [],
      eidtFormRules: {
        email: [
          { required: true, message: '请输入您的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入您的电话', trigger: 'blur' }
        ]
      },
      editFormDialogVisible: false,
      // 控制分配角色对话框的显示和隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选择的角色id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUsers()
    },
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUsers()
    },
    async handleSwitchChange(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        // 为什么这一步能够控制 el-switch 状态？
        // 为什么这一步能够控制 el-switch 状态？
        // 为什么这一步能够控制 el-switch 状态？
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('状态更新失败')
      }
      this.$message.success('状态更新成功')
    },
    handleInputChange() {
      if (this.queryInfo.query === '') {
        this.getUsers()
      }
    },
    dialogClose() {
      this.$refs.addFormRefs.resetFields()
    },
    addUser() {
      this.$refs.addFormRefs.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('users', this.addForm)

        if (res.meta.status !== 201) return this.$message.error('添加用户失败！')

        this.$message.success('添加用户成功！')
        this.addFormDialogVisible = false
        // 刷新用户列表
        this.getUsers()
      })
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败！')
      this.eidtForm = res.data
      this.editFormDialogVisible = true
    },
    // 关闭编辑弹窗后重置表单
    editDialogClose() {
      this.$refs.eidtFormRefs.resetFields()
    },
    editFormConfirm() {
      this.$refs.eidtFormRefs.validate(async valid => {
        if (!valid) {
          return
        }

        const { data: res } = await this.$http.put('users/' + this.eidtForm.id, this.eidtForm)

        if (res.meta.status !== 200) return this.$message.error('用户更新失败')

        // 关闭弹窗
        this.editFormDialogVisible = false
        // 更新列表
        this.getUsers()
        // 提示更新成功
        this.$message.success('用户更新成功')
      })
    },
    // 通过ID删除用户
    async removeUserById(userId) {
      const removeResult = await this.$confirm('此操作将永久删除该用户，是否继续？', '提示', {
        center: true
      }).catch(err => err)

      if (removeResult === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + userId)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')

        this.$message.success('删除用户成功')
        this.getUsers()
      } else {
        this.$message.info('已经取消删除')
      }
    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo

      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }

      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 保存新的用户角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.warning('请选择用户角色')
      }

      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })

      if (res.meta.status !== 200) {
        return this.$message.error(`重新分配角色失败： ${res.meta.msg}`)
      }

      this.getUsers()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style>

</style>
